(function (window,$) {
    var register = {
        auth: function () {
            self = this;
            $('#username').blur(function () {
                self.name();
            });

            $('#email').blur(function () {
                self.email();
            });

            $('#captcha').blur(function () {
                self.captcha();
            })
        },

        name: function () {
            var uname = $('#username').val();
            authUrl = $('#register').attr('action');
            $.ajax({
                url: authUrl+'/auth',
                type: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': $('#token').val()
                },
                data: window.JSON.stringify({
                    content: uname
                }),
                success: function(response) {
                    $('.errUname').html(response.message);
                },
                error: function (err) {
                    console.log(err);
                }
            })
        },
        email: function () {
            var emailValue = $('#email').val();
            authUrl = $('#register').attr('action');
            $.ajax({
                url: authUrl+'/auth',
                type: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': $('#token').val()
                },
                data: window.JSON.stringify({
                    email: emailValue
                }),
                success: function(response) {
                    $('.errEmail').html(response.message);
                },
                error: function (err) {
                    console.log(err);
                }
            })
        },
        captcha: function () {self = this;
            var captchaValue = $('#captcha').val();
            authUrl = $('#register').attr('action');
            $.ajax({
                url: authUrl+'/captcha',
                type: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': $('#token').val()
                },
                data: window.JSON.stringify({
                    captcha: captchaValue
                }),
                success: function(response) {
                    $('.errCaptcha').html(response.message);
                    if(response.message !== null){
                        $('#imgCaptcha').trigger("click");
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            });
        }
    };
    register.auth();
})(window,jQuery);